package com.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reggie.common.BaseContext;
import com.reggie.common.R;
import com.reggie.entity.AddressBook;
import com.reggie.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/addressBook")
@Slf4j
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    /*
    * 添加地址
    * */
    @PostMapping
    public R<String> save(@RequestBody AddressBook addressBook){
        log.info("提交要保存的地址：{}",addressBook.toString());
        //从threadlocal中得到当前用户id，设置进去
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        //将地址存入数据库
        addressBookService.save(addressBook);
        return R.success("地址设置成功");
    }

    /*
    * 查看地址链列表
    * */
    @GetMapping("/list")
    public R<List<AddressBook>> list(){
        log.info("查看地址列表");
        //从threadlocal中得到当前用户id，设置进去
        Long userId = BaseContext.getCurrentId();
        //根据id批量查询
        LambdaQueryWrapper<AddressBook> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId,userId);
        List<AddressBook> list = addressBookService.list(queryWrapper);
        return R.success(list);
    }

    /*
    * 根据id查询单个地址
    * */
    @GetMapping("/{id}")
    public R<AddressBook> getOne(@PathVariable Long id){
        log.info("要编辑的地址的id为：{}",id);
        AddressBook addressBookById = addressBookService.getById(id);
        return R.success(addressBookById);
    }

    /*
    * 设置为默认地址
    * */
    @PutMapping("/default")
    public R<String> setDefault(@RequestBody AddressBook addressBook){
        log.info("设置为默认地址内容：{}",addressBook.toString());
        addressBookService.setDefault(addressBook);
        return R.success("默认地址设置成功");
    }

    /*
    * 编辑地址
    * */
    @PutMapping
    public R<String> update(@RequestBody AddressBook addressBook){
        log.info("编辑的地址为：{}",addressBook.toString());
        addressBookService.updateById(addressBook);
        // return null;
        return R.success("地址修改成功");
    }

    /*
    * 删除地址
    * */
    @DeleteMapping
    public R<String> delete( Long ids){
        log.info("要删除的地址id为：{}",ids);
        addressBookService.removeById(ids);
        return R.success("删除成功");
    }

    /*
    * 获取默认地址
    * */
    @GetMapping("/default")
    public R<AddressBook> getDefault(){
        //获取当前用户id
        Long userId = BaseContext.getCurrentId();
        //根据userId和是否为默认查询默认地址
        LambdaQueryWrapper<AddressBook> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(userId!=null, AddressBook::getUserId,userId).eq(AddressBook::getIsDefault,1);
        AddressBook one = addressBookService.getOne(queryWrapper);
        return R.success(one);
    }
}
